package com.wie.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wie.mapper.ArticleMapper;
import com.wie.pojo.Article;
import com.wie.pojo.PageBean;
import com.wie.service.ArticleService;
import com.wie.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 新增文章
     * @param article
     */
    public void add(Article article) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        article.setCreateUser(userId);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.add(article);
    }

    /**
     * 文章列表查询
     * @param pageNum
     * @param pageSize
     * @param categoryId
     * @param state
     * @return
     */
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 创建pageBean
        PageBean<Article> pageBean = new PageBean<>();
        // 开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        // 调用mapper
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        List<Article> articleList = articleMapper.list(userId, categoryId, state);
        Page<Article> page = (Page<Article>) articleList;
        // 把数据填充到PageBean中
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return pageBean;
    }

    /**
     * 更新文章
     * @param article
     */
    public void update(Article article) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        article.setCreateUser(userId);
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    /**
     * 获取文章详情
     * @param id
     * @return
     */
    public Article detail(Integer id) {
        Article article = articleMapper.getArticleById(id);
        return article;
    }

    /**
     * 删除文章
     * @param id
     */
    public void delete(Integer id) {
        articleMapper.deleteById(id);
    }
}
